package logic

import (
	"context"
	"fmt"
	"user-login/cache"
	"user-login/model/mysql"

	"user-login/userrpc/internal/svc"
	"user-login/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	err := user.FindUser(mysql.DB, in.Mobil)
	if err != nil {
		return nil, err
	}
	result, err := cache.Rdb.Get(cache.Ctx, "SenSms").Result()
	if result != in.SenSms {
		return nil, fmt.Errorf("验证码错误")
	}
	if user.ID != 0 {
		user = mysql.User{
			Mobil:    in.Mobil,
			Password: in.Password,
		}
		err = user.CreatUser(mysql.DB)
		if err != nil {
			return nil, err
		}
	} else {
		if user.Password != in.Password {
			return nil, fmt.Errorf("密码错误")
		}
	}
	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
